function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
}

export function shuffle(arr) {
    let _arr = arr.slice()
    for (let i = 0; i < _arr.length; i++) {
        let j = getRandomInt(0, i)
        let t = _arr[i]
        _arr[i] = _arr[j]
        _arr[j] = t
    }
    return _arr
}

export function debounce(func, delay) {
    let timer

    return function (...args) {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            func.apply(this, args)
        }, delay)
    }
}

export function endWith(target, str) {
    if (str === null || str === '' || target.length === 0 || str.length > target.length) {
        return false
    }
    if (target.substring(target.length - str.length) === str) {
        return true
    } else {
        return false
    }
}

export function getQueryString(param) { // param为要获取的参数名 注:获取不到是为null
    let currentUrl = window.location.href // 获取当前链接
    let arr = currentUrl.split('?')
    if (arr.length > 1) {
        arr = arr[1].split('&')
        for (let i = 0; i < arr.length; i++) {
            let tem = arr[i].split('=') // 分割参数名和参数内容
            if (tem[0] === param) {
                return tem[1]
            }
        }
        return null
    } else {
        return null
    }
}

export function parse2Tree(data, parentId, config) {
    let tree = []
    let temp
    for (let i = 0; i < data.length; i++) {
        let obj = data[i]
        if (obj[config.parentId] === parentId) {
            temp = parse2Tree(data, obj[config.id], config)
            if (temp.length > 0) {
                obj.children = temp
            } else {
                obj.children = []
            }
            tree.push(obj)
        }
    }
    return tree
}

// tree to array转换成一维数组
export function tree2Array(data) {
    let result = []
    for (let i = 0; i < data.length; i++) {
        let obj = data[i]
        result.push(obj)
        if (obj.children && obj.children.length > 0) {
            result = result.concat(tree2Array(obj.children))
        }
    }
    return result
}
